package com.chinasoftinc.facommon;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.utils.TextTool;
import ohos.bluetooth.BluetoothHost;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.RemoteException;
import ohos.utils.net.Uri;

import com.chinasoftinc.facommon.utils.Execute;
import com.chinasoftinc.facommon.utils.ExecuteTask;
import com.chinasoftinc.facommon.utils.LogUtil;

import java.util.Locale;
import java.util.Map;

/**
 * HIlink代理注册
 *
 * @since 2022-05-09
 */
public class HilinkRegister {
    public static final String TAG = "HilinkRegister";
    private static final String HILINK_NET_CONFIG_URI =
        "hilink://hilinksvc.huawei.com/device?action=deviceAdd&prodId=%s&fromApp=%s";
    private String deviceId;
    private String productId;
    private String uuid;
    private Execute waitOpenBluethTask;
    private boolean isAlreadyLogin = false;

    public void configInfo(String productId, String uuid, String deviceId) {
        this.deviceId = deviceId;
        this.productId = productId;
        this.uuid = uuid;
    }

    /**
     * 跳转配网或控制界面判断
     */
    public void goNetConfigOrDevicePage() {
        isAlreadyLogin = true;
        if (TextTool.isNullOrEmpty(deviceId)) {
            if (FAConfigMgr.get().isBleMode()) {
                BluetoothHost bluetoothHost = BluetoothHost.getDefaultHost(FAApplication.getAppContext());
                if (bluetoothHost.getBtState() != BluetoothHost.STATE_ON) {
                    bluetoothHost.enableBt();
                    waitOpenBluetooth();
                    return;
                }
            }
            openHiLinkNetConfig();
        } else {
            openDevicePage();
        }
    }

    private void cancelWaitTasker() {
        if (waitOpenBluethTask != null) {
            waitOpenBluethTask.cancel();
            waitOpenBluethTask = null;
        }
    }

    private void waitOpenBluetooth() {
        cancelWaitTasker();
        waitOpenBluethTask = new Execute();
        waitOpenBluethTask.schedule(new ExecuteTask() {
            @Override
            public void execute() {
                goNetConfigOrDevicePage();
            }
        }, 10 * 1000);
    }

    public void notifyEnableBluetooth() {
        if (isAlreadyLogin) {
            cancelWaitTasker();
            goNetConfigOrDevicePage();
        }
    }

    /**
     * 打开连接页面
     */
    public void openHiLinkNetConfig() {
        FAApplication.getAppContext().getUITaskDispatcher().asyncDispatch(() -> {
            String uriStr = String.format(Locale.ROOT, HILINK_NET_CONFIG_URI, productId, FAConfigMgr.get().getBundleName());
            LogUtil.info(TAG, "openHiLinkNetConfig: uriStr = " + uriStr);
            Intent intent = new Intent();
            intent.setParam("uuid", uuid);
            Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION | Intent.FLAG_NOT_OHOS_COMPONENT)
                .withAction("android.intent.action.VIEW")
                .withUri(Uri.parse(uriStr))
                .build();
            intent.setOperation(operation);
            FAApplication.getAppContext().startAbility(intent, -1);
            publishCloseFaEvent();
        });
    }

    private void publishCloseFaEvent() {
        try {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                .withAction(DeviceControlConstants.ACTION_CLOSE)
                .build();
            intent.setOperation(operation);
            CommonEventData eventData = new CommonEventData(intent);
            CommonEventManager.publishCommonEvent(eventData);
            LogUtil.info(TAG, "Publish succeeded");
        } catch (RemoteException e) {
            LogUtil.error(TAG, "Exception occurred during publishCommonEvent invocation");
        }
    }

    /**
     * 打开设备控制页面
     */
    public void openDevicePage() {
        FAApplication.getAppContext().getUITaskDispatcher().asyncDispatch(() -> {
            Intent intent = new Intent();
            intent.setParam("deviceId", deviceId);
            intent.setParam("uuid", uuid);
            intent.setParam("pid", productId);
            Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(FAConfigMgr.get().getBundleName())
                .withAbilityName(FAConfigMgr.get().getDeviceAbilityName())
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION | Intent.FLAG_INSTALL_ON_DEMAND)
                .build();
            intent.setOperation(operation);
            FAApplication.getAppContext().startAbility(intent, -1);
        });
    }

    public void openDevicePage(Map<String, Object> params) {
        FAApplication.getAppContext().getUITaskDispatcher().asyncDispatch(() -> {
            Intent intent = new Intent();
            intent.setParam("deviceId", deviceId);
            intent.setParam("uuid", uuid);
            intent.setParam("pid", productId);
            params.forEach((s, o) -> {
                if (o instanceof Integer) {
                    intent.setParam(s, (Integer) o);
                } else if (o instanceof Boolean) {
                    intent.setParam(s, (Boolean) o);
                } else {
                    intent.setParam(s, String.valueOf(o));
                }
            });
            Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(FAConfigMgr.get().getBundleName())
                .withAbilityName(FAConfigMgr.get().getDeviceAbilityName())
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION | Intent.FLAG_INSTALL_ON_DEMAND)
                .build();
            intent.setOperation(operation);
            FAApplication.getAppContext().startAbility(intent, -1);
        });
    }


    public static HilinkRegister get() {
        return InnerClass.INSTANCE;
    }

    public static class InnerClass {
        private static final HilinkRegister INSTANCE = new HilinkRegister();
    }
}
